<template>
  <video ref="video" :controls="false" style="width: 100%; height: 100%; object-fit: fill"></video>
</template>

<script>
import Hls from 'hls.js';

export default {
  name: 'HlsPlayer',
  props: {
    src: String,
  },
  mounted() {
    this.$watch(
      () => this.src,
      function (src) {
        // console.log('src: ', src);
        if (typeof src === 'string' && src) this.play(src);
      },
      { immediate: true }
    );
  },
  methods: {
    getPlayer() {
      return new Promise((resolve, reject) => {
        if (this.player) {
          return resolve(this.player);
        }
        if (Hls.isSupported()) {
          this.player = new Hls();
          this.player.on(Hls.Events.MANIFEST_PARSED, () => {
            this.$refs.video.play();
          });
          return resolve(this.player);
        }
        reject();
      });
    },
    play(videoSrc) {
      this.getPlayer().then((player) => {
        // console.log('loadSource: ', videoSrc);
        player.loadSource(videoSrc);
        player.attachMedia(this.$refs.video);
      });
    },
  },
};
</script>
